import Vue from "vue";
import VueRouter from "vue-router";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import login from '../views/auth/Login.vue'
import home from '../views/layout/Home.vue'
import singleSegmentation from "@/components/SingleSegmentation.vue";
import batchSegmentation from "@/components/BatchSegmentation.vue";
import userManagement from "@/components/UserManagement.vue";
import intelligentQA from "@/components/IntelligentQA.vue";
import dataGrip from "@/components/DataGrip.vue";
import singlePageSegmentation from "@/views/segmentation/singlePageSegmentation.vue";
import {checkToken} from "@/api/login";

Vue.use(VueRouter);

const router = new VueRouter({

    routes: [
        {
            path: '/',
            redirect: 'login'
        },
        {
            path: '/login',
            component: login
        },
        {
            path: '/singlePageSegmentation',
            component: singlePageSegmentation
        },
        {
            path: '/home',
            component: home,
            children: [
                {
                    path: 'singleSegmentation',
                    component: singleSegmentation
                },
                {
                    path: 'batchSegmentation',
                    component: batchSegmentation
                },
                {
                    path: 'userManagement',
                    component: userManagement
                },
                {
                    path: 'intelligentQA',
                    component: intelligentQA
                },
                {
                    path: 'dataGrip',
                    component: dataGrip
                }
            ]
        }
    ],
});

//当路由开始跳转时
router.beforeEach((to, from, next) => {
    // 开启进度条
    NProgress.start();
    // 获取token
    const token = sessionStorage.getItem('token')
    //2个不用token的页面请求
    if (to.path === '/login' || to.path === '/register') {
        return next()
    }
    console.log(to.path)
    if (to.path === '/singlePageSegmentation') {
        return next()
    }

    // 如果token存在 先检查下
    if (token) {
        checkToken().then(res => {
            if (res.code !== 200) {
                // token无效 移除token 返回登陆页
                sessionStorage.removeItem('token')
                return next('/login')
            } else {
                return next();
            }
        })
    } else {
        //没有token的情况 直接返回登录页
        return next('/login')
    }
});
//当路由跳转结束后
router.afterEach(() => {
    // 关闭进度条
    NProgress.done()
})

// 将路由实例导出
export default router;